package top.infopub.mgr.hyp.web;


import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import top.infopub.common.ErrorCodeEnum;
import top.infopub.generic.GenericController;
import top.infopub.mgr.common.cnst.Constants;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.hyp.service.HyMenuService;
import top.infopub.mgr.hyp.service.HyPurviewService;
import top.infopub.mgr.hyp.service.HyRolePurviewService;
import top.infopub.mgr.hyp.service.HyRoleService;
import top.infopub.mgr.sys.vo.CheckBoxTreeVo;
import top.infopub.model.hy.Menu;
import top.infopub.model.hy.Purview;
import top.infopub.model.hy.Role;
import top.infopub.model.hy.RolePurview;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.vo.ResponseVo;

import com.github.pagehelper.Page;


/**
 * 会员角色管理
 * @author Awoke
 * @version 2018年10月23日
 * @see HyRoleController
 * @since
 */
@Controller
@RequestMapping("/hyRole")
public class HyRoleController extends GenericController {

    @Autowired
    private HyRoleService roleService;

    @Autowired
    private HyMenuService menuService;

    @Autowired
    private HyPurviewService purviewService;

    @Autowired
    private HyRolePurviewService rolepurviewService;

    /**
     * 角色列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "hyp/hy-role-list";
    }

    /**
     * 根据条件获取获取角色列表数据
     * @param role
     * @return
     */
    @RequestMapping("/queryData")
    public @ResponseBody ResponseVo<Role> queryDataByCondition(Role role, ParamPage paramPage) {
        Page<Role> page = new Page<Role>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = roleService.selectPageByDomainWhere(page, role);
        return ResponseVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 新增/修改
     * @param role
     * @return 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/save")
    public @ResponseBody ResponseVo<Role> save(Role role) {
        // 执行新增
        if (StringUtils.isBlank(role.getId())) {
            if (roleService.isCodeExist(role)) {
                return ErrorCodeEnum.ERROR_COMMON_UNIQUE.getResponseVo("角色编号已经存在~");
            }
            role.setDaddDate(new Date());
            role.setSaddOperator(SessionUserUtils.getSessionUserName());
            roleService.insert(role);
        }
        else// 执行修改
        {
            Role presitRole = roleService.selectByPrimaryKey(role.getId());
            if (presitRole != null) {
                if (!presitRole.getSroleCode().equalsIgnoreCase(role.getSroleCode())) {
                    if (roleService.isCodeExist(role)) {
                        return ErrorCodeEnum.ERROR_COMMON_UNIQUE.getResponseVo("角色编号已经存在~");
                    }
                }
            }
            role.setDmodifyDate(new Date());
            role.setSmodifyOperator(SessionUserUtils.getSessionUserName());
            roleService.updateBySelective(role);
        }
        return ResponseVo.getSuccessResponse(role);
    }

    /**
     * 根据角色ID获取角色
     * @param id
     * @return
     */
    @RequestMapping("/getRoleById")
    public @ResponseBody ResponseVo<Role> getRoleById(String id) {
        Role role = roleService.selectByPrimaryKey(id);
        if (role == null) {
            role = new Role();
        }
        return ResponseVo.getSuccessResponse(role);
    }

    /**
     * 删除角色
     * @param checkboxId
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete")
    public @ResponseBody ResponseVo<String> delete(String[] checkboxId) {
        roleService.delete(checkboxId);
        return ResponseVo.getSuccessResponse();
    }

    /**
     * 保存权限
     * @param checkPurviewId
     * @param roleId
     * @return 
     * @see
     */
    @RequestMapping("/saveRolePurview")
    @SuppressWarnings("unchecked")
    public @ResponseBody ResponseVo<String> saveRolePurview(String checkPurviewId, String roleId) {
        if (StringUtils.isBlank(roleId)) {
            return ErrorCodeEnum.ERROR_COMMON_SYSTEM.getResponseVo(Constants.BAD_PARAMETERS_REQUEST);
        }
        roleService.saveRolePurview(checkPurviewId, roleId);
        return ResponseVo.getSuccessResponse();
    }

    /***
     * 角色分配权限树
     * @return
     */
    @RequestMapping("/getCheckBoxTree")
    public @ResponseBody List<CheckBoxTreeVo> getCheckBoxTree(String roleId) {
        if (null == roleId) {
            return null;
        }
        // 获取所有菜单
        List<Menu> menuList = menuService.selectByEntityWhere(new Menu());
        // 获取所有权限
        List<Purview> listPurview = purviewService.selectByEntityWhere(new Purview());

        RolePurview paramRolepurview = new RolePurview();
        paramRolepurview.setSroleId(roleId);
        List<RolePurview> rolepurviewList = rolepurviewService.selectByEntityWhere(paramRolepurview);
        // 构造treeMap
        Map<String, CheckBoxTreeVo> treeMap = new LinkedHashMap<String, CheckBoxTreeVo>();
        CheckBoxTreeVo root = new CheckBoxTreeVo();
        // 把菜单加到Map里
        for (Menu menu : menuList) {
            CheckBoxTreeVo tree = new CheckBoxTreeVo();
            tree.setBisroot(String.valueOf(menu.getBisRoot()));
            tree.setId(menu.getId());
            tree.setText(menu.getSname());
            tree.setLeaf(false);
            tree.setSparentid(menu.getSparentId());
            tree.setHref("");
            //tree.setIconCls("resource");
            treeMap.put(menu.getId(), tree);
        }
        // 循环所有权限码
        for (Purview purview : listPurview) {
            CheckBoxTreeVo tree = new CheckBoxTreeVo();
            tree.setBisroot("0");
            tree.setId(purview.getId());
            tree.setText(purview.getSpurName());
            tree.setLeaf(true);
            tree.setSparentid(purview.getSparentId());
            if (rolepurviewList != null) {
                Iterator<RolePurview> it = rolepurviewList.iterator();
                while (it.hasNext()) {
                    RolePurview rolepurview = it.next();
                    if (rolepurview.getSpurviewId().equals(purview.getId())) {
                        tree.setChecked(true);
                        break;
                    }
                }
            }
            treeMap.put(purview.getId(), tree);
        }
        // 递归构造树
        Iterator<Map.Entry<String, CheckBoxTreeVo>> it = treeMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, CheckBoxTreeVo> entry = it.next();
            CheckBoxTreeVo tree = entry.getValue();
            if (tree.getBisroot().equals("1")) {// 如果是根节点
                root.getChildren().add(tree);
            }
            else {
                CheckBoxTreeVo parent = treeMap.get(tree.getSparentid());// 根据父Id查询
                if (parent != null) {
                    parent.getChildren().add(tree);
                }
            }
        }
        // 选中有权限码的节点及父节点
        root.removeNoRight();
        root.checkall();
        if (root.getChildren().size() > 0) {
            root.getChildren().get(0).setExpanded(true);
        }
        return root.getChildren();
    }
}
